/*
 * Jobs.java
 * 
 * This file is part of Netuno.
 * 
 * CajuScript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3, or (at your option) 
 * any later version.
 * 
 * CajuScript is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CajuScript.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.netuno;

import org.apache.log4j.Logger;
import org.netuno.psamata.Memory;
import org.netuno.psamata.script.ScriptRunner;
import javax.script.ScriptEngine;

/**
 * Jobs runner.
 * @author eduveks
 */
public class Jobs extends Thread {
    /**
     * Logger.
     */
    private static Logger logger = Logger.getLogger(Jobs.class);
    /**
     * Script Path.
     */
    private String scriptPath = null;
    /**
     * Script Engine.
     */
    private ScriptEngine scriptEngine = null;
    /**
     * Jobs runner.
     */
    public Jobs() {
        scriptPath = ScriptRunner.searchFile("job");
        if (scriptPath != null) {
            scriptEngine = ScriptRunner.getScriptEngineByExtension(scriptPath);
        }
    }
    /**
     * Run.
     */
    public final void run() {
        while (true) {
            try {
                Memory.collectGarbage();
                if (Config.isSendAdminMailActived()) {
                    if (Memory.getMemoryMax() - Memory.getMemoryUsed() <= Config.getMemoryAlert()) {
                        String message = "Memory low capacity!\n\n";
                        message += "Memory Used = ";
                        message += Memory.getMemoryUsed() + " MB\n";
                        message += "Memory Free = ";
                        message += Memory.getMemoryFree() + " MB\n";
                        message += "Memory Max = ";
                        message += Memory.getMemoryMax() + " MB\n";
                        Config.sendAdminMail("Memory Alert!", message);
                    }
                    if (ServiceMonitor.getService() == null) {
                        String message = "All threads busy!\n\n";
                        Service[] services = ServiceMonitor.getServices();
                        for (int x = 0; x < services.length; x++) {
                            message += "Thread[" + x + "] = ";
                            message += ((System.currentTimeMillis()
                            - services[x].getTime())
                            / (60 * 1000F)
                            );
                            message += " Minutes\n";
                        }
                        Config.sendAdminMail("All threads busy!", message);
                    }
                }
                ServiceMonitor.timeout();
                if (scriptEngine != null && scriptPath != null) {
                    try {
                        ScriptRunner.runFile(scriptEngine, scriptPath);
                    } catch (Exception e) {
                        logger.error("Jobs script error.", e);
                    }
                }
                Memory.collectGarbage();
                logger.info("Jobs executed.");
                
                Thread.sleep(Config.getJobsInterval());
            } catch (Exception e) {
                logger.error("Jobs error...", e);
            }
        }
    }
}
